import React, { Component } from 'react'
import { connect } from "react-redux"
import { nanoid } from "nanoid"

import { createAddPersonAction } from "../../redux/action/person"

class Person extends Component {
    pushStudent = () => {
        const nameNode = this.nameNode.value;
        const ageNode = this.ageNode.value;
        const personObj = {
            id: nanoid(),
            name: nameNode,
            age: ageNode
        }
        this.props.addPerson(personObj)
        this.nameNode.value = ""
        this.ageNode.value = ""
    }
    render() {
        const { persons } = this.props
        return (
            <div>
                <h1>我是 Person 组件</h1>
                <h3>上方组件总和为 {this.props.sum}</h3>
                <input ref={c => this.nameNode = c} type="text" placeholder="姓名" />
                <input ref={c => this.ageNode = c} type="text" placeholder="年龄" />
                <button onClick={this.pushStudent}>点击添加</button>
                <ul>
                    {
                        persons.map(item => {
                            return <li key={item.id}>{item.name}---{item.age}</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default connect(
    state => ({
        persons: state.persons,
        sum: state.sum
    }),
    {
        addPerson: createAddPersonAction
    }
)(Person)
